require 'rubygems'
require 'mysql'
require 'open-uri'

OUT_TIME = 1800 #超时时间， 单位：秒
INTERVAL_TIME = 300 #每隔多少秒执行一次脚本
USER = 'root'
PASS = 'amituofo125' #amituofo125
DATABASE = 'sq_iyaoi' #sq_iyaoi
SITE_URL = "http://iyaoi.cn"

def every_n_seconds(n)
 loop do
   yield
   sleep(n)
 end
end

#监测网站
def check_site(url)
  begin
puts url
    open url do |f|
      code = f.status[0]
    end
  rescue
puts "error! 系统即将重启"
    system 'iyaoi'
  end
end

#清楚session
def clear_timeout_sessions(out_time)
  #puts "Clear time out sessions."
  begin
    db = Mysql.real_connect("localhost", USER, PASS, DATABASE)
    #处理CRUD
    db.query("delete from sessions where updated_at <= FROM_UNIXTIME(UNIX_TIMESTAMP(NOW())-#{out_time});")
  rescue MysqlError => e
    print "Error code: ", e.errno, "\n"
    print "Error message: ", e.error, "\n"
  ensure
    #disconnect from server
    db.close unless db.nil?
  end
end

#--------main---------
every_n_seconds(INTERVAL_TIME) do
  check_site(SITE_URL)
  #clear_timeout_sessions(OUT_TIME)
end
